/**
 * 初始化整体客户图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrnumber = require('echarts/util/number');

    var myChart1 = ec.init(document.getElementById('balanceCus')); 
    var myChart2 = ec.init(document.getElementById('balanceOpenCus'));

    var option_1 = {
        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc_1
        },
        legend: {
            data:['会员余额>0客户','非会员余额>0客户']
        },
        toolbox: {
            show : true,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: false},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y: 60,
            y2:20
        },
        dataZoom: {
            show: false,
            realtime : true
        },        
        xAxis: [{
            type: "category",
            position:'top',
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value;
            }}            
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],

        series: [
            {
                name: '总人数',
                type: 'line',
                data:[]
            }
        ]
    };

   var option_2 = {

        tooltip : {
            trigger: 'axis',
            formatter: tooltipFunc_2
        },
        legend: {
             y: 'bottom',
            data:['开通精准客户数','开通置顶客户数','开通智能客户数']
        },
        toolbox: {
            show : false,
            showTitle: true,
            orient:'vertical',
            feature : {
                mark : {show: false},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {          
            y: 35,
            y2:60
        },        
        dataZoom: {
            show: true,
            y: 0,
            height: 20,
            realtime : true,
            start: 90
        },          
        xAxis: [{
            type: "category",
            boundaryGap: true,
            data:[''],
            axisLabel:{formatter:function(value){
                return value;
            }}  
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],

        series: [
            {
                name: '总人数',
                type: 'line',
                data:[]
            }
        ]
    };

var nameMap_userType = {"2":"全部","0":"非会员","1":"会员"};
var nameMap_index = {"balance_0":"余额>0客户","balance_50":"余额>=50客户","cash_balance_0":"现金余额>0客户","cash_balance_50":"现金余额>=50客户","user_num":"有账户客户"};
var nameMap_pro = {'开通精准客户数':"jingzhun_num",'开通置顶客户数':"zhiding_num",'开通智能客户数':"zhineng_num"};

    var index_selected=[];
        // 上下图例一一映射
    var legendMap  = {};
    var legend_1 = [];
    var legend_2 = ['开通精准客户数','开通置顶客户数','开通智能客户数'];
    function setLegend(indexCus_tmp){
        index_selected =indexCus_tmp;
        legend_1 = [];
        legendMap = {};
        $.each(index_selected,function(i,tmp){
            legend_1.push(nameMap_index[tmp]);
        });
        option_1.legend.data = legend_1;
        option_2.legend.data = legend_2;        
    }

    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周，月刷新 , 0: 添加对比后又重新选择指标
     */
    function show(eventType){
        var indexType = $('#index_balance').val();
        var statType = $('#balanceOption').attr('statType');
        var userType = $('#userType_balance').val();
        var cityName = $('#cityName').val();
        var cate = $('#cate_balance').val();
        var businessName = $('#businessName').val();
        nameMap_1 = {};
        var indexCus_tmp = indexType.split(",");
         option_1.legend.data = [];
         option_2.legend.data = [];
        if(indexCus_tmp.length != 2){
            alert("请选择两个指标!");
            return;
        }
        setLegend(indexCus_tmp);
        
        myChart1.showLoading({ text: '正在努力的读取数据中...' });
        myChart2.showLoading({ text: '正在努力的读取数据中...' });
        $.ajax({
            url: '/dashboard/homePage/ajax/balance',
            type: 'post',
            async: true,
            data:{"businessName": businessName, "cityName":cityName, "cate":cate,"userType":userType,"indexType":indexType,"statType":statType,"dataType":"chart"},
            dataType: 'json',
            success: function(data, textStatus) {
                //X轴时间
                option_1.xAxis[0].data = data.time;
                option_2.xAxis[0].data = data.time;
                //上图每条曲线
                var i = 0;
                var series_local = [];
                $.each(indexCus_tmp,function(index,colName){
                    series_local[i++] = {
                        name: legend_1[index],
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        'data': data[colName]
                    };
                });
                option_1.series = series_local;

                //下图每条曲线
                i = 0;
                series_local = [];
                $.each(nameMap_pro,function(colName, dbname){
                    series_local[i++] = {
                        name: colName,
                        type: 'line',
                        smooth: true,
                        symbol:"none",
                        'data': data[dbname]
                    };
                });
                option_2.series = series_local;        

                //区域缩放
                var datezoom_local={
                    day:{start:(1-31/data.time.length)*100,end:100},
                    week:{start:(1-12/data.time.length)*100,end:100},
                    month:{start:0,end:100}
                };
                //少于31个点，全显
                if(data.time.length<31){
                    datezoom_local={
                        day:{start:0,end:100},
                        week:{start:0,end:100},
                        month:{start:0,end:100}
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('month' == statType){
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value.substr(0,4)+"年"+value.substr(4,2)+"月"; } ;
                    }else{
                        option_1.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                        option_2.xAxis[0].axisLabel.formatter=function(value){ return value; } ;
                    }
                    option_1.dataZoom.start=datezoom_local[statType].start;
                    option_1.dataZoom.end=datezoom_local[statType].end;
                    option_2.dataZoom.start=datezoom_local[statType].start;
                    option_2.dataZoom.end=datezoom_local[statType].end;
                    if(eventType == 1 && myChart2.component.dataZoom){
                        myChart1.component.dataZoom.absoluteZoom(datezoom_local[statType]);
                        myChart2.component.dataZoom.absoluteZoom(datezoom_local[statType]);
                        option_2.dataZoom.show=true;
                    }else if(eventType == 2){
                        option_2.dataZoom.show=!$('#time_checkbox_balance').is(":checked"); //false;
                    }
                    myChart1.setOption(option_1,true);
                    myChart2.setOption(option_2,true);
                }else if(eventType == 0){
                    setDataZoom(xAxis_show[0], xAxis_show[xAxis_show.length-1]);
                    myChart1.setOption(option_1,true);
                    myChart2.setOption(option_2,true);
                    if($('#time_input_balance').val()){
                        EC.addCompare_1($('#time_input_balance').val());
                        EC.addCompare_2($('#time_input_balance').val());
                    }
                }
                // myChart.clear();
                myChart1.connect(myChart2);
                myChart2.connect(myChart1);
                myChart1.hideLoading();
                myChart2.hideLoading();
            },
            error : function() {
                myChart1.hideLoading();
                myChart2.hideLoading();
            }
        });
    }

   var ecConfig = require('echarts/config');
    //鼠标click事件
    function eventClick(param){
        var click_date = '2014-01-01';
        if (typeof param.seriesIndex != 'undefined') {
            click_date = param.name;
        }
        loadTableData(click_date);
    }
    myChart1.on(ecConfig.EVENT.CLICK, eventClick);
    myChart2.on(ecConfig.EVENT.CLICK, eventClick);
    //加载27个直销城市当天的数据，, 0:字符, 1:数字, 2:百分比
    var show_cols = {"cate_name":0,"user_num":1,"balance_0":1,"balance_0_chain":2,"cash_balance_0":1,"cash_balance_0_chain":2,"balance_50":1,"balance_50_chain":2,"cash_balance_50":1,"cash_balance_50_chain":2, "jingzhun_num":1,"jingzhun_num_chain":2,"zhiding_num":1,"zhiding_num_chain":2,"zhineng_num":1,"zhineng_num_chain":2};
    function loadTableData(stat_date){
        var indexType = $('#index_balance').val();
        var statType = $('#balanceOption').attr('statType');
        var userType = $('#userType_balance').val();
        var cityName = $('#cityName').val();
        var cate = $('#cate_balance').val();
        var businessName = $('#businessName').val();
        $.ajax({
            url: '/dashboard/homePage/ajax/balance',
            type: 'post',
            async: true,
            data:{"businessName": businessName, "cityName":cityName, "cate":cate,"userType":userType,"indexType":indexType,"statType":statType,"dataType":"table","dateVal":stat_date},
            dataType: 'json',
            success: function(data, textStatus) {
                var resultList = data.dataList;
                var htmlRows = "";
                $.each(resultList,function(i,vo){
                    htmlRows += "<tr>";

                    $.each(show_cols,function(col,colType){
                        switch(colType){
                            case 0:
                                htmlRows += "<td>";
                                htmlRows += vo[col];
                                htmlRows += "</td>";
                                break;
                            case 1:
                                htmlRows += "<td>";
                                htmlRows += zrnumber.addCommas(vo[col]);
                                htmlRows += "</td>";
                                break;
                            case 2:
                                htmlRows += getRate(vo[col]);
                                break;
                            case 3:
                                htmlRows += "<td>";
                                htmlRows += parseFloat(vo[col]).toFixed(2)+"%";
                                htmlRows += "</td>";
                                break;                                   
                        }
                    });

                    htmlRows += "</tr>";
                });

                $('#balanceTable tr:gt(0)').remove();
                $('#balanceTable_date').text(stat_date.replace(/\-/g,"."));
                $('#balanceTable').append(htmlRows);
            },
            error : function() {

            }
        }); 
    }
 
    var all_Options = [option_1,option_2];
    function tooltipFunc_1(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,all_Options[0],"balanceOption");
    }
    function tooltipFunc_2(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,all_Options[1],"balanceOption");
    }
 

   $(function(){
        $("#index_balance_mul").multiselect({
            header:false,
            height:300,
            minWidth:160,
            noneSelectedText: "--请选择--",
            checkAllText: "disabled",
            uncheckAllText: '清空',
            selectedList:2,
            click: function(event, ui){
                var array_of_checked_values = $("#index_balance_mul").multiselect("getChecked").map(function(){
                   return this.value;    
                }).get();
                var warning = $(".message");
                if(array_of_checked_values.length > 2){
                    return false;
                }
                 // $("#cateCmp_cates").val(array_of_checked_values.join(","));
            },
            uncheckAll: function(){
                $("#index_balance").val('');
            },
            selectedText: function(numChecked, numTotal, checkedItems){
                var two='';
                /*
                    js数组的map方法和 $.map(arr,callback)将一个数组中的元素转换到另一个数组中;
                    $(selector).map(arr,callback)返回jquery对象 $(selector).map(arr,callback).get()使用 get() 来处理返回的对象以得到基础的数组
                */
               if(numChecked > 2){
                        return false;
                }
                var checkedVal = checkedItems.map(function(element){
                    return element.value; 
                }).join(',');
                $("#index_balance").val(checkedVal);


                var idcs=checkedItems.map(function(element){
                    // console.log(element.value);
                    return element.labels[0].innerText; 
                }).join(' , ');  

                return idcs;
            }
       });
    }); 

    var chart = new twoLineChart(myChart1, option_1, myChart2, option_2, "balanceOption");
    var EC={
        show:show,
        resize:function(){myChart1.resize();myChart2.resize();},
        hideDataZoom:function(){chart.hideDataZoom()},
        removeCompare:function(){chart.removeCompare()},
        getShowDays:function(){return chart.getShowDays()},
        getAllDays:function(){return chart.getAllDays()},
        addCompare_1:function(time){chart.addCompare_1(time)},
        addCompare_2:function(time){chart.addCompare_2(time)}
    };

    //绑定书刷新按钮点击事件
    $("#refresh_balance_btn").click(function(){
        var type = 2;
        if($('#time_checkbox_balance').is(":checked"))
            type=0;  
        EC.show(type);
    });

    $(":button.btn_balance[statType]").click(function(){
        changeDateGrp(this);
        $('#time_checkbox_balance').attr('checked',false);
        $('#time_input_balance').val('');
        $('#time_input_balance').attr('disabled','');
        if($(this).attr('statType')=='week'){
            $('#time_input_balance').parent().css('visibility',"hidden");
        }else{
            $('#time_input_balance').parent().css('visibility',"visible");
        }
        EC.show(1);
    });

    //时间勾选框事件
    $('#time_checkbox_balance').change(function(e){
        var input=$('#time_input_balance');
        if(!input)return;
        if($(this).is(":checked")){
            input.removeAttr('disabled');
            input.attr('placeholder','选择比较时间起点');               
            EC.hideDataZoom();
            setDatePicker(EC, $('#balanceOption').attr('statType'),input);
        }else{
            input.val('');
            input.attr('disabled','');
            input.attr('placeholder','添加对比');               
            EC.removeCompare();
        }
    });

    //时间选择事件
    $('#time_input_balance').datepicker().on('changeDate',function(e){
        EC.addCompare_1(e.format());
        EC.addCompare_2(e.format());
    });

    return EC;
});

